<template>
    <div class="quiz">
        <el-row :gutter="20" >
            <el-col :span="16">
            <el-button
                type="primary"
                size="medium"
                style="margin-left:5px"
                @click="addQuestionnaireBtn" v-show="isAdmin">添加实验</el-button>
            </el-col>
            <el-col :span="6">
            <el-button
                type="primary"
                size="medium"
                style="margin-left:5px"
                @click="getByPage">查询</el-button>
            </el-col>
        </el-row>
        <div style="margin: 0 0 20px 0">
            <span style="font-size: 25px">实验列表</span>
        </div>
        <el-table v-loading="loading" :data="tableData" border stripe style="width: 60%">
            <el-table-column type="index" label="序号" width="300"></el-table-column>
            <el-table-column prop="title" label="实验标题" width="300"></el-table-column>
            <el-table-column label="实验室介绍" width="300">
                <template slot-scope="scope">
                    <div v-html="scope.row.roomContent"></div>
                </template>
            </el-table-column>
            
            <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                    <el-button type="primary" size="small" icon="el-icon-s-operation" @click="handleClick(scope.row)">开始实验</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[5, 10, 50, 100]"
        :page-size="param.pageSize"
        layout="total, prev, pager, next"
        :total="total">
        </el-pagination>
        <el-dialog
        :visible.sync="addQuestionnaireDialog"
        :title="dialogTitle"
        :show-close="false"
        :close-on-click-modal="false"
        width="80%"
        >
            <el-tabs v-model="activeName" type="card" >
                <el-tab-pane label="添加实验" disabled>
                    <el-form
                    ref="addQuestionnaireForm"
                    :rules="addQuestionnaireFormRule"
                    :model="addQuestionnaireForm"
                    class="addQuestionnaire">
                    <el-form-item label="实验题目" prop="title">
                        <el-input v-model="addQuestionnaireForm.title"/>
                    </el-form-item>
                    <el-form-item label="实验类型" prop="quizType">
                         <el-select v-model="addQuestionnaireForm.quizType" placeholder="请选择">
                            <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="实验简介" prop="roomContent">
                        <quill-editor
                        v-model="addQuestionnaireForm.roomContent"
                        ref="myQuillEditor"
                        :options="editorOption"
                        style="width:96.5%;"
                        >
                        </quill-editor>
                        <!-- <el-input v-model="addQuestionnaireForm.roomContent"/> -->
                    </el-form-item>
                    <!-- <el-form-item label="实验内容" prop="content">
                        <quill-editor
                        v-model="addQuestionnaireForm.content"
                        ref="myQuillEditor"
                        :options="editorOption"
                        style="width:96.5%;"
                        >
                        </quill-editor>
                    </el-form-item> -->
                    <el-form-item>
                    <!-- <el-button size="medium" type="primary" round @click="addQuestionCommitBtn('addQuestionnaireForm')">确定</el-button> -->
                    </el-form-item>
                </el-form>
                </el-tab-pane>
                <el-tab-pane label="预习测试题目" disabled>
                    <el-row>
                        <el-button type="primary" size="small" @click="addQuestion">添加题目</el-button>
                    </el-row>
                    <el-row>
                        <div v-for="(item,index) in previewTestList" :key="index">
                            <span>{{ index+1 }}.{{item.content}}（）</span>
                            <div v-for="(answer,answerIndex) in item.quizAnswerList" :key="answerIndex">
                                <span>{{ handleIdentifyNum(answerIndex) }}.{{ answer.content }}</span>
                            </div>
                        </div>
                    </el-row>
                </el-tab-pane>
                <el-tab-pane label="实验内容" disabled>
                    <!-- <el-form-item label="实验内容" prop="content"> -->
                        <quill-editor
                        v-model="addQuestionnaireForm.content"
                        ref="myQuillEditor"
                        :options="editorOption"
                        style="width:96.5%;"
                        >
                        </quill-editor>
                    <!-- </el-form-item> -->
                </el-tab-pane>
            </el-tabs>
            <el-button size="medium" style="margin-top: 12px;" type="info" v-if="activeName !== '0'"  @click="pre">上一步</el-button>
            <el-button style="margin-top: 12px;" @click="next" v-if="activeName !== '2'">下一步</el-button>
            <el-button size="medium" style="margin-top: 12px;" type="info" v-if="activeName === '0'"  @click="addQuestionCancleBtn('addQuestionnaireForm')">取消</el-button>
            <el-button size="mediun"  style="margin-top: 12px;" v-if="activeName === '2'" @click="saveQuzi">完成</el-button>
        </el-dialog>
        <el-dialog 
        :visible.sync="addQuizQuestionFormDialog"
        :title="questionDialogTitle"
        :show-close="false"
        :close-on-click-modal="false"
        width="60%"
        append-to-body
        >
            <el-form
            ref="addQuizQuestionForm"
            :rules="addQuizQuestionFormRule"
            :model="addQuizQuestionForm"
            class="addQuestionnaire">
                <el-form-item label="预习测试题目" prop="content">
                    <el-input v-model="addQuizQuestionForm.content"/>
                </el-form-item>
                <el-form-item label="选项">
                    <el-table :data="addQuizQuestionForm.quizAnswerList">
                        <el-table-column label="选项内容"  prop="content">
                            <template slot-scope="scope">
                                <el-input  v-model="scope.row.content" ></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="是否为正确答案"  prop="isAnswer">
                            <template slot-scope="{row,$index}">
                                <el-switch  v-model="row.isAnswer" active-color="#13ce66" inactive-color="#ff4949" @change="switchChange(row.isAnswer,$index)"></el-switch>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center">
                            <template slot-scope="{row,$index}">
                                <el-button type="primary" size="small" @click="addAnswer">增加</el-button>
                                <el-button type="primary" size="small" @click="deleAnswer($index)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
            </el-form>
            <el-row>
                <el-button type="primary" size="small" @click="addQuestionAnswer">确定</el-button>
                <el-button type="primary" size="small" @click="addQuizQuestionFormDialog = false">取消</el-button>
            </el-row>
        </el-dialog>
    </div>
</template>

<script>
// import quillEditor from '@/components/quillEditor/quillEditor'
import {quillEditor, Quill} from 'vue-quill-editor'
import {container, ImageExtend, QuillWatch} from 'quill-image-extend-module'
// 普通导入会报错（https://github.com/kensnyder/quill-image-resize-module/issues/7）（jspaine commented on 28 May 2017）
import ImageResize from 'quill-image-resize-module'
Quill.register('modules/ImageExtend', ImageExtend)
Quill.register('modules/imageResize', ImageResize)
    export default {
    data() {
        return {
            options: [{
                value: '001',
                label: '实验一'
                }, {
                value: '002',
                label: '实验三'
                }
            ],
            isAdmin: JSON.parse(localStorage.isAdmin),
            activeName: '0',
            loading: false,
            tableData: [],
            total: 0,
            param: {
                pageSize: 5,
                pageNo: 1
            },
            addQuestionnaireDialog: false,
            dialogTitle: '', // dialog标题
            addQuestionnaireForm: {
                id: null, // 主键
                content: '', // 实验内容
                title: '', // 题目
                questionVoList: [],
                roomContent: '' // 简介
            }, // 添加实验form
            addQuestionnaireFormRule: {
                content: [{ required: true, message: '请完善实验内容', trigger: 'blur' }],
                roomContent: [{ required: true, message: '请输入简介', trigger: 'blur' }],
                quizType: [{ required: true, message: '请选择类型', trigger: 'change' }],
                title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
            },
            editorOption: {
                modules: {
                    ImageExtend: {
                        loading: true,
                        name: 'file',
                        // 图片上传路径
                        action: this.$store.getters.baseUrl + '/fileupload',
                        response: (res) => {
                            // 图片预览路径
                            return this.$store.getters.baseUrl + '/files/' + res.result
                        }
                    },
                    toolbar: {
                        container: container,
                        handlers: {
                            'image': function () {
                                QuillWatch.emit(this.quill.id)
                            }
                        }
                    },
                    imageResize: {
                        displayStyles: {
                            backgroundColor: 'black',
                            border: 'none',
                            color: 'white'
                        },
                        modules: [ 'Resize', 'DisplaySize', 'Toolbar' ]
                    },
                }
            },
            addQuizQuestionFormDialog: false,
            addQuizQuestionForm: {
                content: '',
                score: 4,
                quizId: null,
                quizAnswerList: [{
                    content: '',
                    isAnswer: false
                }] // 选项
            },
            addQuizQuestionFormRule: {
                content: [{ required: true, message: '请输入题目内容', trigger: 'blur' }]
            },
            previewTestList: [],
            questionDialogTitle: ''
        }
    },
    created() {
        
    },
    mounted() {
        this.getByPage()
    },
    methods: {
        handleClickTabs(activeName, oldActiveName) {
            if(activeName === '0') {
                return this.$refs.addQuestionnaireForm.validate()
            }
            if(activeName === '1') {
                return this.$refs.addQuestionnaireForm.validate()
            }
        },
        getByPage() {
            let url = '/quiz/getByPage'
            this.loading = true
            this.$http.post(url,this.param).then(data => {
                this.loading = false
                debugger
                if (data.data.success === true) {
                    // localStorage.username = data.data.userName;
                    this.tableData = data.data.data.records
                    this.total = data.data.data.total
                } else {
                    this.$message.error(data.message);
                }
            }).catch(() => {
                this.loading = false
            })
        },
        // TODO 跳转详情
        handleClick(row) {
            let url = '/userQuiz/getByPage'
            this.$http.post(url,{quizId: row.id, pageNo:1,pageSize: 5}).then(data => {
                if (data.data.success === true) {
                    if(data.data.data.records && data.data.data.records.length > 0) {
                        this.$message.info('你已提交过改实验，不可重复提交')
                    }else {
                        this.$router.push({path:'/quizDetial', query: {quizBaseForm: row}})
                    }
                } else {
                    this.$message.error(data.message);
                }
            }).catch(() => {
            })
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.getByPage()
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.getByPage()
        },
        resetForm(formName) {
            // this.$refs[formName].resetFields()
            this.addQuestionnaireForm = {
                id: null, // 主键
                content: '', // 实验内容
                title: '', // 题目
                roomContent: '' // 简介
            }
        },
        // 添加问卷主题dialog
        addQuestionnaireBtn() {
            this.dialogTitle = '添加实验'
            this.addQuestionnaireDialog = true
        },
        // 问卷主题dialog关闭按钮
        addQuestionCancleBtn(formName) {
            if(this.previewTestList.length !== 5) {
                this.$message.error('请添加五道题目')
                return
            }
            this.$refs[formName].resetFields()
            this.addQuestionnaireDialog = false
        },
        next() {
            if(this.activeName === '0') {
                this.$refs.addQuestionnaireForm.validate(valid => {
                    if(valid) {
                        this.activeName = String(Number.parseInt(this.activeName) + 1)
                    }
                })
            } else {
                this.activeName = String(Number.parseInt(this.activeName) + 1)
            }
        },
        pre() {
            this.activeName = String(Number.parseInt(this.activeName) - 1)
        },
        // 数字标识转化成ABCD
        handleIdentifyNum(index) {
            return String.fromCharCode(parseInt(index + 65))
        },
        addQuestion() {
            this.addQuizQuestionFormDialog = true
            this.questionDialogTitle = '添加题目'
        },
        addAnswer() {
            this.addQuizQuestionForm.quizAnswerList.push({content: '',isAnswer: false})
        },
        deleAnswer(index) {
            debugger
            if(this.addQuizQuestionForm.quizAnswerList === 1) {
                this.$message.error('最后一个选项不能删除')
                return
            }
            this.addQuizQuestionForm.quizAnswerList.splice(index,1)
        },
        switchChange(value,index) {
            debugger
            if(value) {
                for(var i=0;i<this.addQuizQuestionForm.quizAnswerList.length;i++) {
                    if(i !== index) {
                        this.$set(this.addQuizQuestionForm.quizAnswerList[i],'isAnswer',false)
                    }
                }
            }
        },
        addQuestionAnswer() {
            this.previewTestList.push(this.addQuizQuestionForm)
            this.addQuestionnaireForm.questionVoList.push(this.addQuizQuestionForm)
            this.addQuizQuestionFormDialog = false
            this.addQuizQuestionForm= {
                content: '',
                score: 4,
                quizId: null,
                quizAnswerList: [{
                    content: '',
                    isAnswer: false
                }] // 选项
            }

        },
        saveQuzi() {
            debugger
            let url = '/quiz/saveQuiz'
            console.log("addQuestionnaireForm" + JSON.stringify(this.addQuestionnaireForm))
            this.$http.post(url,this.addQuestionnaireForm).then(data => {
                debugger
                if (data.data.success === true) {
                    this.resetQuizForm()
                    this.$message.success('添加成功')
                } else {
                    this.$message.error(data.message);
                }
            })
        },
        resetQuizForm() {
            this.addQuizQuestionFormDialog = false
            this.activeName = '0'
            this.addQuestionnaireForm = {
                id: null, // 主键
                content: '', // 实验内容
                title: '', // 题目
                questionVoList: [],
                roomContent: '' // 简介
            }
            this.addQuizQuestionForm= {
                content: '',
                score: 4,
                quizId: null,
                quizAnswerList: [{
                    content: '',
                    isAnswer: false
                }] // 选项
            }
        }
    }
}
</script>

<style>
.quiz {
    padding: 10px 10px;
    background: #fff;
    display: flex;
    flex-flow: column;
    align-items: center;
}
.addQuestionnaire .el-form-item .el-form-item__label{
  text-align: left;
}
.addQuestionnaire .el-form-item .el-form-item__content{
  margin-left: 100px;
}
.addQuestionnaire .el-form-item .el-form-item__content .el-input{
width: 96.5%;
}
</style>
